package cn.heygod.graywhale.runtime.task;

import cn.heygod.graywhale.runtime.context.Input;
import cn.heygod.graywhale.runtime.context.Output;
import cn.heygod.graywhale.runtime.exception.ServiceException;
import cn.heygod.graywhale.runtime.task.def.TaskDefineManager;
import cn.heygod.graywhale.runtime.task.def.TaskFlowDef;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @className: TaskFlowService
 * @author: Simon
 * @description: TODO
 * @date: 2023/11/22 12:05
 * @version: 1.0
 */
@Component
public class TaskFlowService {

    @Autowired
    private TaskDefineManager taskDefineManager;


    private FlowContainer flowContainer = new FlowContainer();

    public Output start(String flowId, Input input){
        TaskFlowDef flowDef = taskDefineManager.getFlow(flowId);
        if(flowDef == null){
            throw new ServiceException("task flow is not found:"+flowId);
        }
        //创建一个实例并添加到容器中
        TaskFlow flow = flowContainer.createFlow(flowDef);

        return  flow.start(input);
    }



    public static class FlowContainer{
        private ConcurrentMap<String,TaskFlow> flows = new ConcurrentHashMap<>();

        public TaskFlow createFlow(TaskFlowDef flowDef){
            TaskFlow flow = new TaskFlow();
            flow.setDef(flowDef);
            flow.setFlowStatus(TaskFlow.FlowStatus.NEW);
            flow.setFlowId(IdUtil.getSnowflakeNextIdStr());
            flow.setNodes(new ArrayList<>());
            flows.put(flow.getFlowId(),flow);
            return flow;
        }


    }

}
